package com.plant.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.plant.entity.UgcFriends;
import com.plant.entity.UgcUser;
import com.plant.service.FuzzySearchService;
import com.plant.service.HelpService;
import com.plant.service.UserServic;
import com.plant.tool.DateUtils;
import com.plant.tool.Demo;
import com.plant.tool.JavaSmsApi;
import com.plant.tool.ListMapSort;
import com.plant.tool.Test;

/**  1.通过用户的MYID和手机号来搜索用户接口
 *   2.用户通过模糊搜索 搜索植物相关内容
 */
@Controller //注解控制器
@RequestMapping(value = "/search")//注解请求路径
public class FuzzySearchController {

	@Resource(name = "fuzzySearchServiceImpl")//--模糊搜索的接口方法
	private FuzzySearchService fuzzySearchService;

	@Resource(name="helpServiceImpl")
	private HelpService helpService;

	@Resource(name = "userInfoImlp")
	private UserServic userServic;


	@RequestMapping(value="searchfriend")//----1通过好友id和好友手机 
	@ResponseBody
	public Map<String, Object> SearchFriend(Integer user_id,String parmer,UgcUser u,String secret,String pust_val){
		Map<String, Object> map=new HashMap<String, Object>();
		if(secret==null||pust_val==null||user_id==null||parmer==null){
			map.put("error", "参数为空");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mdc=md.md5calc(pust_val+"flower_duigu2016");
			if(secret.endsWith(mdc)){
				int len=parmer.length();
				if(len<7){//----通过MYid来搜索
					u.setMyId(parmer);
					List<Map<String, Object>> userinf=new ArrayList<Map<String,Object>>();
					userinf=fuzzySearchService.FuzzySearchFriend(u);
					if(userinf.size()>0){
						UgcFriends uu=new UgcFriends();
						Integer suid=null;
						for (Map<String, Object> map2 : userinf) {
							suid=(Integer) map2.get("user_id");
						}
						if(user_id.equals(suid)){//自己搜索自己
							map.put("message", "用户不存在");
						}else{
							uu.setReceiveUserId(suid);
							uu.setApplyUserId(user_id);
							boolean b=fuzzySearchService.Isfriend(uu);
							if(b){
								map.put("isfriend", 1);
							}else{
								map.put("isfriend", 0);
							}
							map.put("userinf", userinf);
						}
					}else{
						map.put("message", "用户不存在");
					}
				}else{//---通过用户手机号来搜索
					u.setTel(parmer);
					List<Map<String, Object>> userinf=new ArrayList<Map<String, Object>>();
					userinf=fuzzySearchService.FuzzySearchFriendByTel(u);
					if(userinf.size()>0){
						UgcFriends uu=new UgcFriends();
						Integer suid=null;
						for (Map<String, Object> map2 : userinf) {
							suid=(Integer) map2.get("user_id");
						}
						if(user_id.equals(suid)){// 自己搜索自己 显示用户不存在
							map.put("message", "用户不存在");
						}else{
							uu.setReceiveUserId(suid);
							uu.setApplyUserId(user_id);
							boolean b=fuzzySearchService.Isfriend(uu);
							if(b){
								map.put("isfriend", 1);
							}else{
								map.put("isfriend", 0);
							}
							map.put("userinf", userinf);
						}
					}else{
						map.put("message", "用户不存在");
					}
				}
				return map;
			}else{
				map.put("state", 0);
				map.put("error", "秘钥错误");
				return map;
			}
		}
	}


	@RequestMapping(value="fuzzysearch")//模糊搜索 搜索文章和话题
	@ResponseBody
	public Map<String, Object> FuzzySearch(String parm,String secret,String pust_val){
		Map<String, Object> map=new HashMap<String, Object>();
		if(secret==null||pust_val==null||parm==null){
			map.put("error", "参数为空");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mdc=md.md5calc(pust_val+"flower_duigu2016");
			if(secret.endsWith(mdc)){
				String[] pt=parm.split(" ");
				List<Map<String, Object>> articles=new ArrayList<Map<String,Object>>();
				List<Map<String, Object>> topics=new ArrayList<Map<String,Object>>();
				List<Map<String, Object>> faqs=new ArrayList<Map<String,Object>>();
				for (int i = 0; i < pt.length; i++) {
					String parms=pt[i];
					List<Map<String, Object>> article=new ArrayList<Map<String,Object>>();
					List<Map<String, Object>> topic=new ArrayList<Map<String,Object>>();
					List<Map<String, Object>> faq=new ArrayList<Map<String,Object>>();
					List<Object> list=new ArrayList<Object>();
					article=fuzzySearchService.FuzzySeachArticle(1,parms);
					topic=fuzzySearchService.FuzzySeachTopic(parms);
					faq=fuzzySearchService.FuzzySeachFaq(parms);
					for (Map<String, Object> map1 : article) {
						map1.put("content_type", "1");
						String temp=map1.get("content").toString();
						StringBuffer contents=Test.OnlyChinese(temp);
						int len=contents.indexOf(parms);
						if(len<0){
							String trans=StringEscapeUtils.unescapeHtml4(temp);
							String content=Demo.delHTMLTag(trans);//---将HTML去掉
							map1.put("content", content);
						}else{
							String content=contents.substring(len-parms.length(),contents.length());
							map1.put("content", content);
						}
					}
					for (Map<String, Object> map1 : topic) {
						map1.put("content_type", "2");
					}
					for (Map<String, Object> map2 : faq) {
						map2.put("content_type", "3");
						Object obj=map2.get("id_key");
						list=fuzzySearchService.faqImage(obj);
						String image=list.get(0).toString();
						map2.put("image", image);
					}
					articles.addAll(article);
					topics.addAll(topic);
					faqs.addAll(faq);
				}
				if(articles.size()==0&&topics.size()==0&&faqs.size()==0){
					map.put("message", "无相关内容");
				}else{
					map.put("article", articles);
					map.put("topic", topics);
					map.put("faq", faqs);
				}
				return map;
			}else{
				map.put("state", 0);
				map.put("error", "秘钥错误");
				return map;
			}
		}
	}

	@RequestMapping(value="fuzzysearch_article")//模糊搜索文章 取3条数据显示
	@ResponseBody
	public Map<String, Object> FuzzysearchArticle(String parm,String secret,String pust_val){
		Map<String, Object> map=new HashMap<String, Object>();
		if(secret==null||pust_val==null||parm==null){
			map.put("error", "参数为空");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mdc=md.md5calc(pust_val+"flower_duigu2016");
			if(secret.endsWith(mdc)){
				boolean b=parm.contains(" ");
				if(b){
					parm=parm.replace(" ", "");
				}
				List<Map<String, Object>> article=new ArrayList<Map<String,Object>>();
				List<Map<String, Object>> articles=new ArrayList<Map<String,Object>>();
				article=fuzzySearchService.FuzzySeachArticle(1,parm);
				articles=fuzzySearchService.FuzzySeachArticle(2,parm);
				if(articles.size()>0){
					map.put("hasmore", 1);
				}else{
					map.put("hasmore", 0);
				}
				for (Map<String, Object> map1 : article) {
					map1.put("content_type", "1");
					String temp=map1.get("content").toString();
					StringBuffer contents=Test.OnlyChinese(temp);
					int len=contents.indexOf(parm);
					if(len<0){
						String trans=StringEscapeUtils.unescapeHtml4(temp);
						String content=Demo.delHTMLTag(trans);//---将HTML去掉
						map1.put("content", content);
					}else{
						String content=contents.substring(len,contents.length());
						map1.put("content", content);
					}
					String time=map1.get("create_time").toString();
					map1.put("create_time", DateUtils.StaticTopicCommentTime(DateUtils.StaticgetUnixStamps(time)));
				}
				map.put("article", article);
				map.put("state", 1);
				map.put("message", "搜索文章成功");
				return map;
			}else{
				map.put("state", 0);
				map.put("error", "秘钥错误");
				return map;
			}
		}
	}
	@RequestMapping(value="more_fuzzysearch_article")//更多模糊搜索文章 取10条
	@ResponseBody
	public Map<String, Object> MoreFuzzysearchArticle(Integer page,String time,String parm,String secret,String pust_val){
		Map<String, Object> map=new HashMap<String, Object>();
		if(secret==null||pust_val==null||parm==null||page==null||time==null){
			map.put("error", "参数为空");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mdc=md.md5calc(pust_val+"flower_duigu2016");
			if(secret.endsWith(mdc)){
				boolean b=parm.contains(" ");
				if(b){
					parm=parm.replace(" ", "");
				}
				List<Map<String, Object>> article=new ArrayList<Map<String,Object>>();
				List<Map<String, Object>> articles=new ArrayList<Map<String,Object>>();
				article=fuzzySearchService.MoreFuzzySeachArticle(time, page, parm);
				articles=fuzzySearchService.MoreFuzzySeachArticle(time, page+1, parm);
				if(articles.size()>0){
					map.put("hasmore", 1);
				}else{
					map.put("hasmore", 0);
				}
				for (Map<String, Object> map1 : article) {
					map1.put("content_type", "1");
					String temp=map1.get("content").toString();
					StringBuffer contents=Test.OnlyChinese(temp);
					int len=contents.indexOf(parm);
					if(len<0){
						String trans=StringEscapeUtils.unescapeHtml4(temp);
						String content=Demo.delHTMLTag(trans);//---将HTML去掉
						map1.put("content", content);
					}else{
						String content=contents.substring(len,contents.length());
						map1.put("content", content);
					}
					String create_time=map1.get("create_time").toString();
					map1.put("create_time", DateUtils.StaticTopicCommentTime(DateUtils.StaticgetUnixStamps(create_time)));
				}
				map.put("article", article);
				map.put("state", 1);
				map.put("message", "搜索更多文章成功");
				return map;
			}else{
				map.put("state", 0);
				map.put("error", "秘钥错误");
				return map;
			}
		}
	}

	@RequestMapping(value="fuzzysearch_activity")//模糊搜索活动 取三条数据
	@ResponseBody
	public Map<String, Object> FuzzysearchActivity(String parm,String secret,String pust_val){
		Map<String, Object> map=new HashMap<String, Object>();
		if(secret==null||pust_val==null||parm==null){
			map.put("error", "参数为空");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mdc=md.md5calc(pust_val+"flower_duigu2016");
			if(secret.endsWith(mdc)){
				boolean b=parm.contains(" ");
				if(b){
					parm=parm.replace(" ", "");
				}
				List<Map<String, Object>> activity=new ArrayList<Map<String,Object>>();
				List<Map<String, Object>> activitys=new ArrayList<Map<String,Object>>();
				activity=fuzzySearchService.FuzzySeachActivity(1, parm);
				activitys=fuzzySearchService.FuzzySeachActivity(2, parm);
				if(activitys.size()>0){
					map.put("hasmore", 1);
				}else{
					map.put("hasmore", 0);
				}
				for (Map<String, Object> map1 : activity) {
					map1.put("content_type", "2");
					String time=map1.get("create_time").toString();
					map1.put("create_time", DateUtils.StaticTopicCommentTime(DateUtils.StaticgetUnixStamps(time)));
				}
				map.put("activity", activity);
				map.put("state", 1);
				map.put("message", "查询成功");
				return map;
			}else{
				map.put("state", 0);
				map.put("error", "秘钥错误");
				return map;
			}
		}
	}


	@RequestMapping(value="more_fuzzysearch_activity")//模糊搜索活动 取10条数
	@ResponseBody
	public Map<String, Object> MoreFuzzysearchActivity(Integer page,String time,String parm,String secret,String pust_val){
		Map<String, Object> map=new HashMap<String, Object>();
		if(secret==null||pust_val==null||parm==null||page==null||time==null){
			map.put("error", "参数为空");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mdc=md.md5calc(pust_val+"flower_duigu2016");
			if(secret.endsWith(mdc)){
				boolean b=parm.contains(" ");
				if(b){
					parm=parm.replace(" ", "");
				}
				List<Map<String, Object>> activity=new ArrayList<Map<String,Object>>();
				List<Map<String, Object>> activitys=new ArrayList<Map<String,Object>>();
				activity=fuzzySearchService.MoreFuzzySeachActivity(time, page, parm);
				activitys=fuzzySearchService.MoreFuzzySeachActivity(time, page+1, parm);
				if(activitys.size()>0){
					map.put("hasmore", 1);
				}else{
					map.put("hasmore", 0);
				}
				for (Map<String, Object> map1 : activity) {
					map1.put("content_type", "2");
					String create_time=map1.get("create_time").toString();
					map1.put("create_time", DateUtils.StaticTopicCommentTime(DateUtils.StaticgetUnixStamps(create_time)));
				}
				map.put("activity", activity);
				map.put("state", 1);
				map.put("message", "查询更多活动成功");
				return map;
			}else{
				map.put("state", 0);
				map.put("error", "秘钥错误");
				return map;
			}
		}
	}

	@RequestMapping(value="fuzzysearch_faq")//2页面模糊搜索问答
	@ResponseBody
	public Map<String, Object> TestFuzzysearchFaq(String parm,String secret,String pust_val,Integer page){
		Map<String, Object> map=new HashMap<String, Object>();
		if(secret==null||pust_val==null||parm==null||page==null){
			map.put("error", "参数为空");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mdc=md.md5calc(pust_val+"flower_duigu2016");
			if(secret.endsWith(mdc)){
				//    			String parm="花";
				boolean b=parm.contains(" ");
				SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				if(b){
					map.put("message", "搜索关键不能带空格");
					map.put("state", "0");
				}else{
					List<Map<String, Object>> faq=new ArrayList<Map<String,Object>>();
					List<Map<String, Object>> faq2=new ArrayList<Map<String,Object>>();
					List<Object> list=new ArrayList<Object>();
					List<Object> answerids=new ArrayList<Object>();
					faq=fuzzySearchService.FuzzySeachFaqPaging(parm, page);
					faq2=fuzzySearchService.FuzzySeachFaqPaging(parm, page);
					int faq2len=faq2.size();
					if(faq2len>0){
						map.put("hasmore", 1);
					}else{
						map.put("hasmore", 0);
					}
					for (Map<String, Object> map2 : faq) {
						Object obj=map2.get("id_key");
						Object user_id=map2.get("user_id");
						Object content_id=map2.get("content_id");
						Object content=map2.get("content");
						UgcUser u=(UgcUser) userServic.UserPartInf(user_id);
						map2.put("user_id", u.getId());
						map2.put("nickname", u.getNickname());
						map2.put("photo", u.getPhoto());
						Timestamp temp=(Timestamp) map2.get("create_time");
						String t=sim.format(temp);
						long l=DateUtils.StaticgetUnixStamps(t);
						map2.put("create_time", DateUtils.StaticTopicCommentTime(l));
						map2.put("answer_count", helpService.OneFaqAnswerCount(obj));
						answerids=fuzzySearchService.AllAnswerIds(obj);
						int len1=answerids.size();
						if(len1>0){
							String ids=StringUtils.join(answerids.toArray(),",");
							map2.put("count_like", fuzzySearchService.CountAllFaqAnswerCount(ids));
						}else{
							map2.put("count_like", 0);
						}
						if(content_id==null&&content==null){
							list=fuzzySearchService.OneFaqAnswer(obj);
							int len=list.size();
							if(len==0){
								map2.put("content", "");
							}else{
								map2.put("content", list.get(0));
							}
						}
						map2.remove("COUNT(DISTINCT a.id)");
					}
					ListMapSort.Sort(faq);
					map.put("faq", faq);
				}
				return map;
			}else{
				map.put("state", 0);
				map.put("error", "秘钥错误");
				return map;
			}
		}
	}


	@RequestMapping(value="invited_friend")//通过手机通讯录邀请好友下载我们的APP
	@ResponseBody
	public Map<String, Object> InvitedFriend(String mobile,String username,String secret,String pust_val){
		Map<String, Object> map=new HashMap<String, Object>();
		if(secret==null||pust_val==null||username==null||mobile==null){
			map.put("error", "参数为空");
			map.put("state", 0);
			return map;
		}else{
			Md md=new Md();
			String mdc=md.md5calc(pust_val+"flower_duigu2016");
			if(secret.endsWith(mdc)){
				String apikey = "b8fe6db82ce852bda647575a9304765d";
				String regExg="^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
				Pattern p = Pattern.compile(regExg);
				Matcher m = p.matcher(mobile); 
				if(m.find()){
					if(username.length()<6){
						String text="【植物先生】您的通讯录联系人"+username+"邀请你玩植物先生APP,快来看看吧!http://www.zhiwuxiansheng.com/view/webview/article.html?id=236&from=singlemessage";//---添加短信模板
						try {
							String result=JavaSmsApi.sendSms(apikey, text, mobile);
							System.out.println(result);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}else{
						String text="【植物先生】您的通讯录联系人"+username+"邀请你玩植物先生APP,快来看看吧!http://www.zhiwuxiansheng.com/view/webview/article.html?id=236&from=singlemessage";//---添加短信模板
						try {
							String result=JavaSmsApi.sendSms(apikey, text, mobile);
							System.out.println(result);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					map.put("message", "邀请成功");
					map.put("state", "1");
				}else{
					map.put("state", "0");
					map.put("message", "查看手机号是否正确");
				}

				return map;
			}else{
				map.put("state", 0);
				map.put("error", "秘钥错误");
				return map;
			}
		}
	}

}
